const path = require('path');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MyWebpackPlugin = require('./plugin/myPlugin');
const webpack = require('webpack');

module.exports = {
  mode: 'development',
  entry: {
    spcTool: './src/index.js'
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'scripts/[name]-[hash:5].js',
    library: {
      type: 'umd',
      name: 'spc'
    },
    // 新增配置，指定全局对象
    globalObject: 'typeof self!== \'undefined\'? self : global'
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    },
    extensions: ['.js', '.css'], // 解析扩展名
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /\.(css|less)$/i,
        use: ['style-loader', {
          loader: 'css-loader',
          options: {
            modules: true
          }
        }, 'less-loader']
      },
      {
        test: /\.(png|jpg|jpeg|gif)$/i,
        type: 'asset',
        generator: {
          filename: 'images/[name][hash:5].[ext]'
        }
      }
    ]
  },
  plugins: [
    new MyWebpackPlugin(), // 自定义插件
    new CleanWebpackPlugin(), // 清除dist目录
    new HtmlWebpackPlugin({ // 生成html文件
      template: './public/index.html'
    }),
    new webpack.DefinePlugin({ // 定义全局变量
      VERSION: `'1.0.1'`,
      DOMAIN: JSON.stringify('https://www.zdy.com')
    }),
    new webpack.BannerPlugin({ // 添加版权注释
      banner: 'zdy-webpack-plugin'
    })
  ],
  devServer: {
    port: 8080,
    open: true,
    proxy: [
      {
        '/api': {
          target: 'http://localhost:3000',
          changeOrigin: true,
        }
      }
    ],
  },
  stats: {
    colors: true,
    modules: false,
  }
};
